package com.module.lemlin.mode

import androidx.annotation.CallSuper
import androidx.lifecycle.MutableLiveData
import com.module.lemlin.rxhttp.HttpServiceData
import com.module.lemlin.rxhttp.HttpServiceResponse
import com.module.lemlin.rxhttp.Status


interface SubscribeListener<HttpData : HttpServiceData> {

    fun onStart()

    fun onSuccess(resp: HttpData)

    fun onFailure(throwable: Throwable)
}

open class ViewModelSubscribe<HttpData : HttpServiceData>(
    private val liveData: MutableLiveData<HttpServiceResponse<HttpData>>?
) : SubscribeListener<HttpData> {
    @CallSuper
    override fun onStart() {
        with(receiver = liveData?.value ?: HttpServiceResponse()) {
            this.status = Status.START
            liveData?.postValue((this))
        }
    }

    override fun onSuccess(resp: HttpData) {
        with(receiver = liveData?.value ?: HttpServiceResponse()) {
            this.status = Status.SUCCESS
            this.httpData = resp
            liveData?.postValue((this))
        }
    }

    @CallSuper
    override fun onFailure(throwable: Throwable) {
        with(receiver = liveData?.value ?: HttpServiceResponse()) {
            this.status = Status.FAILURE
            this.throwable = throwable
            liveData?.postValue((this))
        }
    }
}